"""日期时间格式相关的衍生配置处理"""

from typing import Dict, Any
from ...type.types import MySQLTypeInfo, MiaomaType
from ...type.converters import MySQLToMiaomaTypeConverter
from src.base import bera

def derive_datetime_formats(meta_info: Dict[str, Any]) -> Dict[str, Any]:
    """处理日期时间格式的衍生配置

    为每个日期相关的字段添加格式配置:
    - columns.*.derived.java.datetime_format: Java格式化字符串
    - columns.*.derived.ts.datetime_format: TypeScript格式化字符串
    - columns.*.derived.ui.datetime_format: UI显示格式
    - columns.*.derived.ui.show_time: 是否显示时间选择器
    """

    # 格式转换映射
    FORMAT_MAPPINGS = {
        MiaomaType.MIAOMA_BASE_DATE: {
            'java': 'yyyy-MM-dd',
            'ts': 'YYYY-MM-DD',
            'ui': 'YYYY-MM-DD',
            'show_time': False
        },
        MiaomaType.MIAOMA_BASE_DATETIME: {
            'java': 'yyyy-MM-dd HH:mm:ss',
            'ts': 'YYYY-MM-DD HH:mm:ss',
            'ui': 'YYYY-MM-DD HH:mm:ss',
            'show_time': True
        },
        MiaomaType.MIAOMA_BASE_TIMESTAMP: {
            'java': 'yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\'',  # Java ISO 格式
            'ts': 'YYYY-MM-DDTHH:mm:ss.SSS[Z]',          # dayjs ISO 格式
            'ui': 'YYYY-MM-DD HH:mm:ss',                 # 用户友好的显示格式
            'show_time': True
        }
    }

    for column_name, column_info in meta_info["columns"].items():
        try:
            # 从column_info中提取类型信息
            sql_type = column_info["sql"]["type"]
            type_info = MySQLTypeInfo(
                name=sql_type["name"].upper(),
                length=sql_type.get("length"),
                precision=sql_type.get("precision"),
                scale=sql_type.get("scale")
            )

            # 转换为 MiaomaType
            miaoma_type = MySQLToMiaomaTypeConverter.convert(
                mysql_type=type_info.name,
                length=type_info.length,
                precision=type_info.precision,
                scale=type_info.scale
            )

            # 如果是日期相关类型，设置格式配置
            if miaoma_type in FORMAT_MAPPINGS:
                format_mapping = FORMAT_MAPPINGS[miaoma_type]

                # 确保derived配置存在
                if "derived" not in column_info:
                    column_info["derived"] = {}

                # 设置Java格式
                if "java" not in column_info["derived"]:
                    column_info["derived"]["java"] = {}
                column_info["derived"]["java"]["datetime_format"] = format_mapping['java']

                # 设置TypeScript格式
                if "ts" not in column_info["derived"]:
                    column_info["derived"]["ts"] = {}
                column_info["derived"]["ts"]["datetime_format"] = format_mapping['ts']

                # 设置UI显示格式
                if "ui" not in column_info["derived"]:
                    column_info["derived"]["ui"] = {}
                column_info["derived"]["ui"]["datetime_format"] = format_mapping['ui']
                column_info["derived"]["ui"]["show_time"] = format_mapping['show_time']

        except Exception as e:
            bera.logger.warning(f"处理列 {column_name} 的日期时间格式时出错: {str(e)}")
            continue

    return meta_info